package com.gutai.admin.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import com.gutai.admin.common.entity.dto.UserCouponDto;
import com.gutai.admin.common.util.IdGeneratorUtil;
import com.gutai.admin.dao.ICartDao;
import com.gutai.admin.dao.IUserDao;
import com.gutai.admin.entity.Cart;
import com.gutai.admin.entity.User;
import com.gutai.admin.entity.UserCoupon;
import com.gutai.admin.service.ICouponService;
import com.gutai.admin.service.IUserService;


/**
 * 
 * 
 * 
 * <pre>
 * HISTORY
 * ****************************************************************************
 *  ID    DATE            PERSON            REASON
 *  1     2019年1月29日         la.01367604           Create
 * ****************************************************************************
 * </pre>
 * 
 * @author la.01367604
 * @version 1.0
 */
@Service
@CacheConfig(cacheNames = "shopUser")
public class UserService implements IUserService {

    @Autowired
    private IUserDao userDao;
    @Autowired
    private ICouponService couponService;
    @Autowired
    private ICartDao cartDao;

    @Override
    public List<User> getAll() {
        return userDao.findAll();
    }

    @Override
    public Page<User> getList(Integer startPage, Integer pageSize) {
        return userDao.queryPage(startPage, pageSize);
    }

    @Override
    @CacheEvict(allEntries = true)
    public void add(User entity) {
        entity.setId(IdGeneratorUtil.generate());
        userDao.save(entity);
    }

    @Override
    @CacheEvict(allEntries = true)
    public void update(User entity) {
        userDao.saveAndFlush(entity);
    }

    @Override
    @Cacheable(key = "'ID$'+#id", unless = "#result == null")
    public User findById(int id) {
        return userDao.findById(id);
    }

    @Override
    @Cacheable(key = "'name$'+#name", unless = "#result == null || #result.size()==0")
    public List<User> findByName(String name) {
        return userDao.findByUsername(name);
    }

    @Override
    @CacheEvict(allEntries = true)
    public void delete(int id) {
        userDao.deleteById(id);
    }

    @Override
    public List<UserCouponDto> getByUserId(Integer userId) {
        List<UserCoupon> userCoupons = couponService.getByUserId(userId);
        return userCoupons.stream().map(userCoupon -> new UserCouponDto(userCoupon, couponService.findById(userCoupon.getCouponId()))).collect(Collectors.toList());
    }
    
    @Override
    @Cacheable(key = "'cart$'+#userId", unless = "#result == null || #result.size()==0")
    public List<Cart> getCartByUserId(Integer userId) {
        return cartDao.findByUserId(userId);
    }
}
